package 路径问题;

import java.util.Scanner;

public class test4 {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int m = in.nextInt();
        int n = in.nextInt();
        int[][] nums  = new int[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                nums[i][j] = in.nextInt();
            }
        }
        System.out.println(minFallingPathSum(nums));
    }

    public static int minFallingPathSum(int[][] matrix) {
        int m = matrix.length;
        int n = matrix[0].length;
        int[][] dp = new int[m+2][n+2];

        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
                if(j==1)
                    dp[i][j] = Math.min(dp[i-1][j],dp[i-1][j+1])+matrix[i-1][j-1];
                else if (j==n)
                    dp[i][j] = Math.min(dp[i-1][j-1],dp[i-1][j])+matrix[i-1][j-1];
                else
                    dp[i][j] = Math.min(Math.min(dp[i-1][j-1],dp[i-1][j]),dp[i-1][j+1])+matrix[i-1][j-1];
            }
        }
        int flag = Integer.MAX_VALUE;
        for (int i = 1; i <= n; i++) {
            if(dp[m][i]<flag)
                flag = dp[m][i];
        }
        return flag;
    }
}
